﻿using Core.Configuration.Api;
using Core.Configuration.Config;
using IconYuan.Api.Services;
using IconYuan.Manager.Orders;
using IconYuan.Manager.Products;
using IconYuan.Manager.Stores;
using IconYuan.Manager.Users;
using IconYuan.Model.DB;
using IconYuan.Model.DTO.Orders;
using IconYuan.Model.Entity.Orders;
using IconYuan.Model.Entity.Stores;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace IconYuan.Api.Controllers.Orders
{
    /// <summary>
    /// 订单操作
    /// </summary>
    public class OrderController : ApiBase
    {
        readonly OrderManager orderSvc;
        readonly OrderGoodsManager orderGoodsSvc;
        readonly OrderTraceManager orderTraceSvc;
        readonly ShopManager shopSvc;
        readonly SkuManager skuSvc;
        readonly UserManager userSvc;
        public OrderController()
        {
            orderSvc = new OrderManager();
            orderGoodsSvc = new OrderGoodsManager();
            orderTraceSvc = new OrderTraceManager();
            shopSvc = new ShopManager();
            skuSvc = new SkuManager();
            userSvc = new UserManager();
        }
        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="user_id">用户id: 0 所有会员</param>
        /// <param name="status">状态:0 所有订单, 30 调理中, 70 已完成</param>
        /// <param name="page">第几页</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageList<OrderDto>> List(int user_id, int status, int page = 1)
        {
            var expGoods = Expressionable.Create<OrderGoods>();
            var expShop = Expressionable.Create<Shop>();
            var exp = Expressionable.Create<Order>();
            exp.And(x => x.jump == 1);
            exp.AndIF(user_id > 0, x => x.user_id == user_id);
            if (status > 0)
                exp.And(x => x.order_status == status);
            else
            {
                var statusList = new List<int>() { 30, 70 };
                exp.And(x => statusList.Contains(x.order_status));
            }
            
            var result = await orderSvc.GetPageListAsync(exp.ToExpression(), y => y.order_id, OrderByType.Desc, page);
            result.data.ForEach(x =>
            {
                expGoods.Or(y => y.order_id == x.order_id);
                expShop.Or(y => y.shop_id == x.shop_id);
            });

            var shopList = await shopSvc.GetListAsync(expShop.ToExpression());
            var goodsList = await orderGoodsSvc.GetListAsync(expGoods.ToExpression(), y => y.order_id, OrderByType.Desc);
            foreach (var goods in goodsList)
            {
                goods.goods_image = $"{GlobalConfig.CdnDomain}{goods.goods_image}";
            }

            var list = result.data.Select(x => OrdersServices.ToOrderDto(x, goodsList, shopList)).ToList();
            return new PageList<OrderDto>()
            {
                data = list,
                current_page = result.current_page,
                last_page = result.last_page,
                per_page = result.per_page,
                total = result.total,
            };
        }

        /// <summary>
        /// 订单详情
        /// </summary>
        /// <param name="order_id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<OrderDto> Order(int order_id)
        {
            var order = await orderSvc.GetAsync(order_id);
            if (order == null) throw new Exception("订单不存在");

            var goodsList = await orderGoodsSvc.GetListAsync(x => x.order_id == order_id);
            foreach (var goods in goodsList)
            {
                goods.goods_image = $"{GlobalConfig.CdnDomain}{goods.goods_image}";
                goods.skuInfo = await skuSvc.GetAsync(x => x.goods_id == goods.goods_id && x.goods_sku_id == goods.goods_sku_id);
            }

            var shopList = new List<Shop>();
            if (order.shop_id > 0)
                shopList.Add(shopSvc.Get(order.shop_id));

            return OrdersServices.ToOrderDto(order, goodsList, shopList);
        }

        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> SetStatus(OrderStatusDto model)
        {
            if (model.order_id < 1) throw new Exception("请填写订单id");
            if (model.status < 1) throw new Exception("请填写状态");
            if (model.manage_user_id < 1) throw new Exception("请填写工作人员id");

            var user = await userSvc.GetAsync(x => x.user_id == model.manage_user_id);
            if (user.user_type < 1) throw new Exception("你不是工作人员");

            var result = await orderSvc.UpdateAsync(x => new Order() { order_status = model.status }, y => y.order_id == model.order_id);
            if (result)
            {
                await orderTraceSvc.InsertAsync(new OrderTrace()
                {
                    order_id = model.order_id,
                    status = model.status,
                    create_time = DateTime.Now,
                    describe = OrdersServices.GetTraceDesc(model.status),
                });
            }
            return result;
        }
    }
}